<!DOCTYPE html>
<html lang="en">
  <head>
    <meta charset="UTF-8" />
    <meta name="viewport" content="width=device-width, initial-scale=1.0" />
    <title>Document</title>
  </head>
  <body>
    <h3>商品价格列表</h3>
    <input type="checkbox" name="item" value="1500" /> 山地自行车1500<br />
    <input type="checkbox" name="item" value="200" /> 时尚女装200<br />
    <input type="checkbox" name="item" value="3000" /> 笔记本电脑3000元<br />
    <input type="checkbox" name="item" value="800" /> 情侣手表800<br />
    <input type="checkbox" name="item" value="2000" /> 桑塔纳2000<br />
    <hr />
    <input type="checkbox" id="all" onclick="selectAll()" /><label for="all"
      >全选/全不选 &nbsp;</label
    >
    <input
      type="button"
      id="reverse"
      onclick="reverseSelect()"
      value=" 反 选 "
    />&nbsp; <input type="button" value=" 结 账 " onclick="total()" />&nbsp;
    <span id="result"></span>

    <script>
      // 获取全选按钮
      let allBtn = document.querySelector("#all");

      let items = document.querySelectorAll("input[name=item]");

      let result = document.querySelector("#result");

      for (let i = 0; i < items.length; i++) {
        // 给每一项添加点击事件
        items[i].onclick = function () {
          checkStatus();
        };
      }

      /*
        全选
      */
      function selectAll() {
        // 获取全选按钮的状态
        let status = allBtn.checked;
        for (let i = 0; i < items.length; i++) {
          items[i].checked = status;
        }
      }

      function reverseSelect() {
        for (let i = 0; i < items.length; i++) {
          items[i].checked = !items[i].checked;
        }
        // 检测选中状态
        checkStatus();
      }

      function checkStatus() {
        let checkedItems = document.querySelectorAll(
          "input[name=item]:checked"
        );

        if (checkedItems.length === items.length) {
          // 全选按钮选中
          allBtn.checked = true;
        } else {
          allBtn.checked = false;
        }
      }

      function total() {
        let checkedItems = document.querySelectorAll(
          "input[name=item]:checked"
        );

        let sum = 0;
        for (let index = 0; index < checkedItems.length; index++) {
          const element = checkedItems[index];
          sum += parseFloat(element.value);
        }
        console.log(sum);

        result.innerHTML = "总价：<mark>" + sum + "</mark>元";
      }
    </script>
  </body>
</html>
